package com.zzy.controller;

import com.zzy.datagridlist.Datagrid;
import com.zzy.model.Menu;
import com.zzy.service.MenuService;
import com.zzy.service.UtilService;
import com.zzy.util.AjaxMsg;
import com.zzy.util.UtilJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Controller()
@RequestMapping("menu")
public class MunuController {

    @Autowired
    private MenuService menuService;
    @Autowired
    private UtilService utilService;

    /**跳转到列表页面*/
    @RequestMapping(value="index")
    public String index(HttpServletRequest request, HttpServletResponse response){
       return "page/menu/menu_index";
    }
    /**获取数据表格内容*/
    @RequestMapping(value="gird")
    @ResponseBody
    public void gird(HttpServletRequest request, HttpServletResponse response){
        Datagrid.list(request,response,Menu.class,utilService);
    }


    /**跳转到详情页面*/
    @RequestMapping(value="load")
    public String load(HttpServletRequest request, HttpServletResponse response){
        String id = request.getParameter("id");
        String parentId = request.getParameter("parentId");
        if(id!=null){//查看或修改
            Menu menu = menuService.getByID(id);
            request.setAttribute("model",menu);
            request.setAttribute("load",request.getParameter("load"));
        }
        if(StringUtils.hasText(parentId)){//父级
            Menu parent = menuService.getByID(parentId);
            request.setAttribute("parent",parent);
        }
        return   "page/menu/menu_detail";
    }

    /**添加或者修改*/
    @RequestMapping(value="opt")
    @ResponseBody
    public void addOrUpdate(Menu model, HttpServletRequest request, HttpServletResponse response){
        if(model!=null && model.getId()!=null && model.getId().trim().equals("")){//保证传递的ID不是空值 而是null
            model.setId(null);
        }
        UtilJson.jsonPrintln(menuService.saveOrUpdate(model),response);
    }

    /**删除*/
    @RequestMapping(value="delete")
    @ResponseBody
    public void delete(String id,HttpServletRequest request, HttpServletResponse response){
        UtilJson.jsonPrintln(menuService.delTree(id),response);;
    }

    /**验证用户是否存在*/
    @RequestMapping(value="tree")
    @ResponseBody
    public void check(HttpServletRequest request, HttpServletResponse response){
        String html = menuService.getTreeHtml(null);
        UtilJson.jsonPrintModel(AjaxMsg.returnAjaxMsg(html),response);
    }
}
